package com.ByteDance.service.impl;

import com.ByteDance.model.po.FavoriteEntity;
import com.ByteDance.mapper.FavoriteMapper;
import com.ByteDance.model.po.Relation;
import com.ByteDance.model.po.UserInfos;
import com.ByteDance.model.po.VideoEntity;
import com.ByteDance.model.vo.User;
import com.ByteDance.model.vo.Video;
import com.ByteDance.service.IFavoriteService;
import com.ByteDance.service.IRelationService;
import com.ByteDance.service.IUserService;
import com.ByteDance.service.IVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;

/**
 * <p>
 * 视频点赞表 服务实现类
 * </p>
 *
 * @author 朱哥
 * @since 2024-03-03
 */
@Service
@RequiredArgsConstructor
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, FavoriteEntity> implements IFavoriteService {

    private final IRelationService iRelationService;
    private final IUserService iUserService;
    private final IVideoService iVideoService;
    @Override
    public Boolean action(int userId, int videoId, int actionType) {
        VideoEntity videoEntity = iVideoService.getById(videoId);
        //根据videoId查出authorId
        int authorId = videoEntity.getAuthorId();
        //根据authorId查出作者信息
        UserInfos authorInfos = iUserService.getById(authorId);
        //根据userId查出自己的信息
        UserInfos userInfos = iUserService.getById(userId);
        if(actionType == 1){
            //点赞操作--点赞表增加一条记录
            //1.先查找是否已经点赞过该视频
            FavoriteEntity entity = lambdaQuery().eq(FavoriteEntity::getVideoId, videoId).eq(FavoriteEntity::getUserId, userId).one();
            if(entity != null){//点赞过
                return false;
            }
            //2.构建FavoriteEntity
            FavoriteEntity favoriteEntity = new FavoriteEntity();
            favoriteEntity.setUserId(userId);
            favoriteEntity.setVideoId(videoId);
            baseMapper.insert(favoriteEntity);
            //author获赞数量+1,userId对应喜欢数+1,视频的favorite_count + 1
            iUserService.lambdaUpdate()
                    .set(UserInfos::getTotalFavorited,authorInfos.getTotalFavorited() + 1)
                    .eq(UserInfos::getTotalFavorited,authorInfos.getTotalFavorited())   //authorId对应的获赞总数等于我刚刚查到的获赞总数才更新
                    .eq(UserInfos::getUserId,authorId)
                    .update();
            iUserService.lambdaUpdate()
                    .set(UserInfos::getFavoriteCount,userInfos.getFavoriteCount() + 1)
                    .eq(UserInfos::getFavoriteCount,userInfos.getFavoriteCount())   //userId对应的喜欢数等于我刚刚查到的喜欢数才更新
                    .eq(UserInfos::getUserId,userId)
                    .update();
            iVideoService.lambdaUpdate()
                    .set(VideoEntity::getFavoriteCount,videoEntity.getFavoriteCount() + 1)
                    .eq(VideoEntity::getVideoId,videoId)
                    .eq(VideoEntity::getFavoriteCount,videoEntity.getFavoriteCount()) //videoId对应的喜欢数等于我刚刚查到的喜欢数
                    .update();
            return true;
        }else if(actionType == 2){
            //1.先查找是否已经点赞过该视频
            FavoriteEntity entity = lambdaQuery().eq(FavoriteEntity::getVideoId, videoId).eq(FavoriteEntity::getUserId, userId).one();
            if(entity == null){//没有点赞过
                return false;
            }
            //取消点赞--点赞表减少一条记录
            QueryWrapper<FavoriteEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId).eq("video_id",videoId);
            baseMapper.delete(queryWrapper);
            //author获赞数量-1,userId对应喜欢数-1，视频的favorite_count + 1
            iUserService.lambdaUpdate()
                    .set(UserInfos::getTotalFavorited,userInfos.getTotalFavorited() - 1)
                    .eq(UserInfos::getTotalFavorited,userInfos.getTotalFavorited())   //authorId对应的获赞总数等于我刚刚查到的获赞总数才更新
                    .eq(UserInfos::getUserId,authorId)
                    .update();
            iUserService.lambdaUpdate()
                    .set(UserInfos::getFavoriteCount,userInfos.getFavoriteCount() - 1)
                    .eq(UserInfos::getFavoriteCount,userInfos.getFavoriteCount())   //userId对应的喜欢数等于我刚刚查到的喜欢数才更新
                    .eq(UserInfos::getUserId,userId)
                    .update();
            iVideoService.lambdaUpdate()
                    .set(VideoEntity::getFavoriteCount,videoEntity.getFavoriteCount() - 1)
                    .eq(VideoEntity::getVideoId,videoId)
                    .eq(VideoEntity::getFavoriteCount,videoEntity.getFavoriteCount()) //videoId对应的喜欢数等于我刚刚查到的喜欢数
                    .update();
            return true;
        }
        //既不是1也不是2--不合法
        return false;
    }

    @Override
    public Video[] searchFavoriteByUserId(int userId) {
        List<FavoriteEntity> list = lambdaQuery().eq(FavoriteEntity::getUserId, userId).list();
        Video[] videos = new Video[list.size()];
        for (int i = 0; i < list.size(); i++) {
            FavoriteEntity favoriteEntity = list.get(i);
            VideoEntity videoEntity  = iVideoService.getById(favoriteEntity.getVideoId());
            //查询作者信息
            int authorId= videoEntity.getAuthorId();
            UserInfos author = iUserService.getById(authorId);
            User user = new User();
            user.setUserId(authorId);
            user.setUsername(author.getUsername());
            user.setFollowCount(author.getFollowCount());
            user.setFollowerCount(author.getFollowerCount());
            //查询该userId是否关注了authorId
            boolean flag = true;
            Relation relation = iRelationService.lambdaQuery().eq(Relation::getFollowId, authorId).eq(Relation::getFollowerId, userId).one();
            if(relation == null){
                flag = false;
            }
            user.setFollow(flag);
            user.setAvatar(author.getAvatar());
            user.setBackgroundImage(author.getBackgroundImage());
            user.setSignature(author.getSignature());
            user.setTotalFavorited(author.getTotalFavorited());
            user.setWorkCount(author.getWorkCount());
            user.setFavoriteCount(author.getFavoriteCount());
            videos[i] = new Video();
            videos[i].setId(videoEntity.getVideoId());
            videos[i].setAuthor(user);
            videos[i].setCommentCount(videoEntity.getCommentCount());
            videos[i].setPlayurl(videoEntity.getPlayUrl());
            videos[i].setCoverurl(videoEntity.getCoverUrl());
            videos[i].setFavoriteCount(videoEntity.getFavoriteCount());
            //既然是查看点赞列表，那一定是点赞了
            videos[i].setFavorite(true);
            videos[i].setTitle(videoEntity.getTitle());
        }
        return videos;
    }

    @Override
    public boolean isFavorite(Integer videoId, Integer userId) {
        FavoriteEntity favoriteEntity = lambdaQuery().eq(FavoriteEntity::getVideoId, videoId)
                .eq(FavoriteEntity::getUserId, userId).one();
        if(favoriteEntity == null){
            return false;
        }
        return true;
    }

}
